package org.whh.automatic.ui;

import org.whh.automatic.model.Step;

import javax.swing.*;
import java.awt.*;
import java.io.Serial;
import java.util.HashMap;
import java.util.Map;

/**
 * 动态值设置对话框
 */
public class DynamicValueDialog extends JDialog {

    @Serial
    private static final long serialVersionUID = 1L;

    // 颜色常量
    private static final Color HEADER_GRADIENT_START = new Color(65, 105, 225);
    private static final Color HEADER_GRADIENT_END = new Color(100, 149, 237);
    private static final Color BORDER_COLOR = new Color(210, 210, 210);
    private static final Color BUTTON_BACKGROUND = new Color(70, 130, 180);
    private static final Color BUTTON_HOVER = new Color(30, 144, 255);
    private static final Color BUTTON_TEXT = Color.WHITE;

    private Map<String, JTextField> valueFields = new HashMap<>();
    private Map<String, String> dynamicValues = new HashMap<>();
    private boolean confirmed = false;


    /**
     * 构造函数 - 使用步骤和动态值名称映射
     *
     * @param parent              父窗口
     * @param title               标题
     * @param stepDynamicValueMap 步骤和动态值名称映射
     */
    public DynamicValueDialog(JFrame parent, String title, Map<Step, String> stepDynamicValueMap) {
        super(parent, title, true);

        initComponentsWithSteps(stepDynamicValueMap);

        // 设置合适的大小和位置
        int rows = Math.max(1, stepDynamicValueMap.size());
        int height = Math.min(800, 400 + rows * 80);
        setSize(700, height);
        setLocationRelativeTo(parent);
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    }

    /**
     * 初始化三列布局（步骤、动态值名称、动态值内容）
     */
    private void initComponentsWithSteps(Map<Step, String> stepDynamicValueMap) {
        this.dynamicValues = new HashMap<>();
        this.valueFields = new HashMap<>();
        confirmed = false;

        // 设置窗口风格
        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout(0, 0)) {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setColor(Color.WHITE);
                g2d.fillRect(0, 0, getWidth(), getHeight());
                g2d.dispose();
            }
        };
        mainPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));

        // 创建标题面板
        JPanel titlePanel = new JPanel(new BorderLayout()) {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                GradientPaint gp = new GradientPaint(0, 0, HEADER_GRADIENT_START, 0, getHeight(), HEADER_GRADIENT_END);
                g2d.setPaint(gp);
                g2d.fillRect(0, 0, getWidth(), getHeight());
                g2d.dispose();
            }
        };
        titlePanel.setPreferredSize(new Dimension(650, 60));

        JLabel titleLabel = new JLabel("设置动态值");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        titleLabel.setForeground(Color.WHITE);
        titleLabel.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0));
        titlePanel.add(titleLabel, BorderLayout.WEST);

        // 添加标题面板
        mainPanel.add(titlePanel, BorderLayout.NORTH);

        // 内容面板使用BoxLayout
        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
        contentPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createEmptyBorder(20, 20, 20, 20),
                BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(BORDER_COLOR, 1),
                        BorderFactory.createEmptyBorder(20, 20, 20, 20)
                )
        ));
        contentPanel.setBackground(Color.WHITE);

        // 说明标签
        JLabel infoLabel = new JLabel("<html><b>请为所有动态值设置实际值后再运行任务。</b></html>");
        infoLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        infoLabel.setForeground(new Color(50, 50, 50));
        infoLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

        JPanel infoPanel = new JPanel();
        infoPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
        infoPanel.setBackground(Color.WHITE);
        infoPanel.add(infoLabel);
        infoPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, 60));

        contentPanel.add(infoPanel);
        contentPanel.add(Box.createVerticalStrut(20));

        // 表头面板 - 调整为表格式布局
        JPanel headerPanel = new JPanel(new GridLayout(1, 3, 0, 0));
        headerPanel.setBackground(new Color(240, 240, 240));
        headerPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(180, 180, 180)),
                BorderFactory.createEmptyBorder(15, 5, 15, 5)
        ));
        headerPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, 50));

        // 控制每列宽度的面板
        JPanel col1Header = new JPanel(new BorderLayout());
        col1Header.setBackground(new Color(240, 240, 240));
        JPanel col2Header = new JPanel(new BorderLayout());
        col2Header.setBackground(new Color(240, 240, 240));
        JPanel col3Header = new JPanel(new BorderLayout());
        col3Header.setBackground(new Color(240, 240, 240));

        JLabel stepHeaderLabel = new JLabel("步骤名称");
        stepHeaderLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        stepHeaderLabel.setForeground(new Color(60, 60, 60));
        stepHeaderLabel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));

        JLabel nameHeaderLabel = new JLabel("动态值名称");
        nameHeaderLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        nameHeaderLabel.setForeground(new Color(60, 60, 60));
        nameHeaderLabel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));

        JLabel valueHeaderLabel = new JLabel("动态值内容");
        valueHeaderLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        valueHeaderLabel.setForeground(new Color(60, 60, 60));
        valueHeaderLabel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));

        col1Header.add(stepHeaderLabel, BorderLayout.WEST);
        col2Header.add(nameHeaderLabel, BorderLayout.WEST);
        col3Header.add(valueHeaderLabel, BorderLayout.WEST);

        headerPanel.add(col1Header);
        headerPanel.add(col2Header);
        headerPanel.add(col3Header);

        contentPanel.add(headerPanel);
        contentPanel.add(Box.createVerticalStrut(10));

        // 数据行面板
        JPanel rowsPanel = new JPanel();
        rowsPanel.setLayout(new BoxLayout(rowsPanel, BoxLayout.Y_AXIS));
        rowsPanel.setBackground(Color.WHITE);

        // 为每个步骤-动态值对创建输入框
        for (Map.Entry<Step, String> entry : stepDynamicValueMap.entrySet()) {
            Step step = entry.getKey();
            String dynamicValueName = entry.getValue();

            JPanel rowPanel = new JPanel(new GridLayout(1, 3, 0, 0));
            rowPanel.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(230, 230, 230)),
                    BorderFactory.createEmptyBorder(15, 5, 15, 5)
            ));
            rowPanel.setBackground(Color.WHITE);
            rowPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, 60));

            // 控制每列宽度的面板
            JPanel col1 = new JPanel(new BorderLayout());
            col1.setBackground(Color.WHITE);
            JPanel col2 = new JPanel(new BorderLayout());
            col2.setBackground(Color.WHITE);
            JPanel col3 = new JPanel(new BorderLayout());
            col3.setBackground(Color.WHITE);

            JLabel stepLabel = new JLabel(step.getName());
            stepLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
            stepLabel.setForeground(new Color(80, 80, 80));
            stepLabel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));

            JLabel nameLabel = new JLabel(dynamicValueName);
            nameLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
            nameLabel.setForeground(new Color(80, 80, 80));
            nameLabel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));

            JTextField valueField = new JTextField();
            valueField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
            valueField.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(200, 200, 200), 1),
                    BorderFactory.createEmptyBorder(5, 8, 5, 8)
            ));
            valueFields.put(dynamicValueName, valueField);

            col1.add(stepLabel, BorderLayout.WEST);
            col2.add(nameLabel, BorderLayout.WEST);
            col3.add(valueField, BorderLayout.CENTER);

            rowPanel.add(col1);
            rowPanel.add(col2);
            rowPanel.add(col3);

            rowsPanel.add(rowPanel);
        }

        contentPanel.add(rowsPanel);

        // 创建按钮面板
        JPanel buttonPanel = createButtonPanel();

        // 添加到滚动面板
        JScrollPane scrollPane = new JScrollPane(contentPanel);
        scrollPane.setBorder(null);
        scrollPane.getVerticalScrollBar().setUnitIncrement(16);

        // 添加到主面板
        mainPanel.add(scrollPane, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        // 设置主面板
        setContentPane(mainPanel);
    }

    /**
     * 创建按钮面板
     */
    private JPanel createButtonPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 15, 15));
        panel.setBackground(Color.WHITE);
        panel.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, BORDER_COLOR));

        JButton cancelButton = createStyledButton("取消");
        cancelButton.addActionListener(e -> dispose());

        JButton confirmButton = createStyledButton("确定");
        confirmButton.addActionListener(e -> {
            if (validateInputs()) {
                collectValues();
                confirmed = true;
                dispose();
            }
        });

        panel.add(cancelButton);
        panel.add(confirmButton);

        return panel;
    }

    /**
     * 创建带样式的按钮
     */
    private JButton createStyledButton(String text) {
        JButton button = new JButton(text) {
            @Override
            protected void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                if (getModel().isPressed()) {
                    g2.setColor(BUTTON_BACKGROUND.darker());
                } else if (getModel().isRollover()) {
                    g2.setColor(BUTTON_HOVER);
                } else {
                    g2.setColor(BUTTON_BACKGROUND);
                }

                g2.fillRoundRect(0, 0, getWidth(), getHeight(), 8, 8);
                g2.setColor(BUTTON_TEXT);

                int textWidth = g2.getFontMetrics().stringWidth(getText());
                int textHeight = g2.getFontMetrics().getHeight();
                g2.drawString(getText(), (getWidth() - textWidth) / 2,
                        (getHeight() - textHeight) / 2 + g2.getFontMetrics().getAscent());

                g2.dispose();
            }
        };

        button.setPreferredSize(new Dimension(120, 35));
        button.setFont(new Font("微软雅黑", Font.BOLD, 14));
        button.setForeground(BUTTON_TEXT);
        button.setBackground(BUTTON_BACKGROUND);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        button.setContentAreaFilled(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        return button;
    }

    /**
     * 验证输入的动态值
     */
    private boolean validateInputs() {
        for (Map.Entry<String, JTextField> entry : valueFields.entrySet()) {
            String name = entry.getKey();
            String value = entry.getValue().getText().trim();

            if (value.isEmpty()) {
                JOptionPane.showMessageDialog(this,
                        "请为 '" + name + "' 设置动态值",
                        "动态值缺失",
                        JOptionPane.WARNING_MESSAGE);
                entry.getValue().requestFocus();
                return false;
            }
        }

        return true;
    }

    /**
     * 收集动态值
     */
    private void collectValues() {
        dynamicValues.clear();
        for (Map.Entry<String, JTextField> entry : valueFields.entrySet()) {
            dynamicValues.put(entry.getKey(), entry.getValue().getText().trim());
        }
    }

    /**
     * 用户是否确认了动态值设置
     */
    public boolean isConfirmed() {
        return confirmed;
    }

    /**
     * 获取设置的动态值
     */
    public Map<String, String> getDynamicValues() {
        return dynamicValues;
    }
}
